package com.jiguang.property.controller;

import com.alipay.easysdk.factory.Factory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiguang.property.dto.UpkeepInfoDTO;
import com.jiguang.property.entity.BuildInfo;
import com.jiguang.property.entity.CostInfo;
import com.jiguang.property.service.ApiPayService;
import com.jiguang.property.service.BuildInfoService;
import com.jiguang.property.service.CostInfoService;
import com.jiguang.property.service.UpkeepInfoService;
import com.jiguang.property.utils.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@RestController
@RequestMapping("/apiPay")
@CrossOrigin
public class ApiPayController {
    @Autowired
    private ApiPayService apiPayService;
    @Autowired
    private UpkeepInfoService upkeepInfoService;
    @Autowired
    private CostInfoService costInfoService;

    @GetMapping("pay")
    public Result pay(String orderNo,Double price,String urge,HttpServletResponse response) throws Exception {
        String result = null;
        try {
            //返回的是from标签
            result = apiPayService.createDownLineTrading(orderNo,price,urge);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  我们只需要将返回的这个标签进行跳转就行了，二维码是跳转之后就出来的，不用考虑获取二维码
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();

        return Result.ok();
    }

    @GetMapping("/success")
    @ResponseBody
    public String success(String urge,HttpServletRequest request,HttpServletResponse response) throws Exception {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 验签通过
            System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));


        String targetUrl = "http://localhost:8080/maintenance";
        if(!StringUtils.isEmpty(urge)){
            targetUrl = "http://localhost:8080/payFees";
            CostInfo costInfo = new CostInfo();
            costInfo.setId(tradeNo);
            costInfo.setStatus(1);
            costInfoService.updateById(costInfo);
        }else{
            // 更新订单未已支付
            UpkeepInfoDTO upkeepInfoDTO = new UpkeepInfoDTO();
            upkeepInfoDTO.setId(tradeNo);
            upkeepInfoDTO.setStatus(3);
            upkeepInfoService.updateOrAddUpkeepInfo(upkeepInfoDTO);
        }

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write("<!DOCTYPE html><html><head>"
                + "<meta http-equiv='refresh' content='0;url=" + targetUrl + "'>"
                + "</head><body>正在跳转...</body></html>");
        out.flush();

        return "success";
    }
}
